package com.lft.juc01.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Function: 		A {@code SailTickets} object With Some FUNCTION.<br/>
 * Reason:   		ADD REASON.<br/>
 * Date:            2021-01-28 20:12<br/>
 * <p>
 * Class Name:      SailTickets<br/>
 * Package Name:    com.lft.juc01.base<br/>
 * @author Laifengting / E-mail:laifengting@foxmail.com
 * @version 1.0.0
 * @since JDK 8
 */
public class SailTickets {
	public static void main(String[] args) {
		// 并发：多线程操作同一个资源类，把资源类丢入线程中。
		Ticket ticket = new Ticket();
		new Thread(() -> {for (int i = 0; i < 40; i++)ticket.sale();}, "A").start();
		new Thread(() -> {for (int i = 0; i < 40; i++)ticket.sale();}, "B").start();
		new Thread(() -> {for (int i = 0; i < 40; i++)ticket.sale();}, "C").start();
	}
}

/**
 * Lock 三部曲
 * 1. 创建锁对象 new ReentrantLock();
 * 2. 加锁 lock.lock();
 * 3. 解锁 lock.unlock();
 */
class Ticket {
	// 字段
	private int number = 30;
	Lock lock = new ReentrantLock();
	
	// 方法
	public void sale() {
		// 加锁
		lock.lock();
		try {
			// 业务代码
			if (number > 0) {
				System.out.println(Thread.currentThread().getName() + " 卖出了 " + number-- + " 票，剩余 " + number);
			}
		} finally {
			// 释放锁
			lock.unlock();
		}
	}
}
